<template>
  <div style="height: 100%">
    <div>
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item>
          <el-input v-model="searchForm.name" placeholder="机构名" v-if="sys_dept_view" clearable @clear="findByPage"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="findByName" size="medium" v-if="sys_dept_view" icon="el-icon-search">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="add" size="medium" v-if="sys_dept_add" icon="el-icon-plus">新增</el-button>
        </el-form-item>
        <el-form-item style="float: right">
          <el-tooltip content="刷新" placement="top">
            <el-button icon="el-icon-refresh-right" circle @click="findByPage"></el-button>
          </el-tooltip>
        </el-form-item>
      </el-form>
      <v-table row-key="deptId" :columns="columns" :data="tableData" :table-operation="tableOperation"
               :loading="loadingData"
               @handleClick="handleClick" @loadChildren="loadChildren" @findPage="findByPage">
        <template slot="operation" slot-scope="scope">
          <el-button
            v-if="sys_dept_view"
            @click="handleView(scope.data.row)"
            :size="viewOperation.size || 'mini'"
            :style="{color: viewOperation.color|| ''}"
            :icon="viewOperation.icon"
            type="text">
            {{viewOperation.name}}
          </el-button>
          <el-button
            v-if="sys_dept_edit"
            @click="handleEdit(scope.data.row)"
            :size="editOperation.size || 'mini'"
            :style="{color: editOperation.color|| ''}"
            :icon="editOperation.icon"
            type="text">
            {{editOperation.name}}
          </el-button>
          <el-button
            v-if="sys_dept_delete"
            @click="handleDelete(scope.data.row)"
            :size="deleteOperation.size || 'mini'"
            :style="{color: deleteOperation.color|| ''}"
            :icon="deleteOperation.icon"
            type="text">
            {{deleteOperation.name}}
          </el-button>
        </template>
      </v-table>
      <el-dialog :title="title" :visible.sync="dialogFormVisible" width="40%">

        <el-form :model="deptForm" label-width="80px" class="demo-ruleForm">
          <el-form-item label="机构名称" prop="name" required>
            <el-input v-model="deptForm.name" placeholder="请输入机构名称" :disabled="view"></el-input>
          </el-form-item>
          <el-form-item label="上级机构" prop="parentName">
            <el-popover
              ref="popover"
              placement="bottom"
              trigger="click"
              :disabled="view"
              v-model="popoverVisible">
              <el-input
                :size="size"
                placeholder="输入关键字进行过滤"
                v-model="filterText">
              </el-input>
              <el-tree
                :data="deptTree"
                :props=" { children: 'children', label: 'name' }"
                :filter-node-method="filterNode"
                ref="tree"
                @node-click="handleNodeClick"></el-tree>
            </el-popover>
            <el-input v-model="deptForm.parentName" placeholder="请选择父级机构" :disabled="view" @focus="findDeptTree" v-popover:popover :readonly="true"></el-input>
          </el-form-item>
          <el-form-item label="排序" prop="sort">
            <el-input-number v-model="deptForm.sort" controls-position="right" :disabled="view"></el-input-number>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="save" v-show="!view" v-if="saveVisible">保 存</el-button>
          <el-button type="primary" @click="update" v-show="!view" v-else>更 新</el-button>
        </div>

      </el-dialog>
    </div>

  </div>
</template>

<script>
  import vueTable from '../../../components/vueTable.vue'
  import {deptApi} from '../../../http/modules/dept'
  import VTable from "../../../components/table/table";
  import website from "../../../const/website";
  import {mapGetters} from "vuex";

  export default {
    name: "dept",
    components: {
      VTable,
      vueTable
    },
    data() {
      return {
        tableData: {
          totalSize: 0,
          content: []
        },
        pageRequest: {
          pageNum: 1,
          pageSize: 10
        },
        columns: [
          {prop: "name", label: "名称", minWidth: 100},
          {prop: "sort", label: "排序", minWidth: 80},
          {prop: "createTime", label: "创建时间", minWidth: 80}
        ],
        tableOperation: {
          operation: true
        },
        viewOperation: website.viewOperation, // 查看操作
        editOperation: website.editOperation, // 编辑操作
        deleteOperation: website.deleteOperation, // 删除操作
        searchForm: {
          name: '',
          pageNum: 1,
          pageSize: 10
        },
        selections: [],
        dialogFormVisible: false,
        saveVisible: true,
        title: '新增',
        deptForm: {
          name: '',
          sort: 1,
          parentId: '',
          parentName: ''
        },
        loadingData: true,
        popoverVisible: false,
        filterText: '',
        deptTree: [],
        size: 'mini',
        view: false
      }
    },
    methods: {
      findByPage(data) {
        if (data != null) {
          this.pageRequest = data
        }
        if (this.searchForm.name !== '' && data != null) {
          this.searchForm.pageNum = data.pageNum
          this.findByName()
        } else {
          deptApi.findPage(this.pageRequest).then(res => {
            this.loadingData = false
            this.tableData = res.data
          }).catch(error => {
            console.log(error)
            this.$message.error('网络错误')
          })
        }

      },
      findByName() {
        this.loadingData = true
        deptApi.findByName(this.searchForm).then(res => {
          this.loadingData = false
          this.tableData = res.data
        }).catch(error => {
          console.log(error)
          this.$message.error('网络错误')
        })
      },
      add() {
        this.dialogFormVisible = true
        this.saveVisible = true
        this.title = '新增'
      },
      cancel() {
        this.dialogFormVisible = false
      },
      save() {
        deptApi.save(this.deptForm).then(res => {
          this.$message.success('新增成功')
          this.dialogFormVisible = false
          this.findByPage()
        }).catch(error => {
          this.$message.error('新增失败')
        })

      },
       handleClick(row, type) {
         let rows = []
         if (type === 'delete') {
           rows.push(row)
           this.handleDelete(rows)
         } else if(type === 'edit') {
           this.handleEdit(row)
         } else if(type === 'view') {
           this.handleView(row)
         }
      },
      handleView(data) {
        this.title = '查看'
        this.dialogFormVisible = true
        this.deptForm = data
        this.view = true
      },
      handleEdit(data) {
        // 修改机构信息
        this.dialogFormVisible = true
        this.view = false
        this.saveVisible = false
        this.title = '编辑'
        this.deptForm = data

        if (data.parentId !== null) {
          this.deptForm.parentName = this.getParentName(this.tableData.content, data.parentId)
        }

      },
      getParentName(values, deptId) {
        for (let i = 0; i < values.length; i++) {
          if (values[i].deptId === deptId) {
            return values[i].name
          }
          if (values[i].children.length > 0) {
            this.getParentName(values.children, deptId)
          }
        }
      },
      update() {
        deptApi.update(this.deptForm).then(res => {
          this.$message.success('更新成功')
        }).catch(error => {
          this.$message.error('更新失败')
        })
        this.dialogFormVisible = !this.dialogFormVisible
      },
      handleDelete(rows) {
        // 删除用户
        this.$confirm('此操作将删除机构，是否继续？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.delete(rows)
        }).catch(() => {
          this.$message.info('已取消删除')
        })
      },
      delete(datas) {
        let records = []
        datas.forEach(item => {
          records.push({deptId: item.deptId})
        })
        deptApi.delete(records).then(res => {
          this.$message.success('删除成功')
          this.findByPage()
        }).catch(error => {
          this.$message.error('删除失败')
        })
      },

      selectionChange(selections) {
        this.selections = selections
      },
      clearDeptForm() {
        this.deptForm = {
          name: '',
          sort: '',
          parentId: '',
          parentName: ''
        }
      },
      /**
       * 加载子菜单
       */
      loadChildren(row, treeNode, resolve) {
        deptApi.findChildrenDeptById(row.deptId).then(data => {
          resolve(data.data)
        })
      },
      filterNode(value, data) {
        if (!value) return true;
        return data.name.indexOf(value) !== -1;
      },
      handleNodeClick(data) {
        this.deptForm.parentName = data.name
        this.deptForm.parentId = data.deptId
        this.popoverVisible = false
      },
      findDeptTree() {
        deptApi.findDeptTree().then(data => {
          this.deptTree = data.data
        }).catch(error => {
          console.log(error)
        })
      },
    },
    watch: {
      dialogFormVisible(val, oldValue) {
        console.log(val)
        if (!val) {
          this.clearDeptForm()
        }
      }
    },
    computed: {
      ...mapGetters(["permissions"])
    },
    created() {
      this.sys_dept_view = this.permissions["sys:dept:view"]
      this.sys_dept_add = this.permissions["sys:dept:add"]
      this.sys_dept_edit = this.permissions["sys:dept:edit"]
      this.sys_dept_delete = this.permissions["sys:dept:delete"]
    },
    mounted() {
      // this.findByPage(this.pageRequest)
    }
  }
</script>

<style scoped>

</style>
